extends CanvasLayer

@onready var resume: Button = $Left/Resume
@onready var load: Button = $Left/Load
@onready var last_save: Label = $Left/LastSave


func _ready() -> void:
	hide()
	visibility_changed.connect(func ():
		get_tree().paused = visible
	)


func show_pause() -> void:
	get_tree().get_first_node_in_group("player").virtual_joypad.visible = false
	show()
	update_save_version()
	resume.grab_focus()


func _input(event: InputEvent) -> void:
	if event.is_action_pressed("pause"):
		hide()
		get_window().set_input_as_handled()


func _on_resume_pressed() -> void:
	hide()
	get_tree().get_first_node_in_group("player").virtual_joypad.visible = true


func _on_load_pressed() -> void:
	Game.load_game()


func _on_save_pressed() -> void:
	Game.save_game()
	update_save_version()


func _on_quit_pressed() -> void:
	get_tree().quit()


func update_save_version() -> void:
	var file := FileAccess.open(Game.SAVE_PATH, FileAccess.READ)
	if not file:
		load.disabled = true
		load.hide()
		last_save.hide()
		return
	
	load.disabled = false
	load.show()
	var json := file.get_as_text()
	var data := JSON.parse_string(json) as Dictionary
	var save := data.save_time as String
	last_save.text = "Last Save: " + save
	last_save.show()


func _on_new_pressed() -> void:
	Game.new_game()
